class Billiard2 extends egret.DisplayObjectContainer {
    private ball0: Ball
    private ball1: Ball
    public constructor() {
        super()
        this.once( egret.Event.ADDED_TO_STAGE, this.onAddToStage, this)
    }

    private onAddToStage(evt: egret.Event):void {
        this.ball0 = new Ball(40)
        this.ball0.mass = 2
        this.ball0.x = 50
        this.ball0.y = this.stage.stageHeight / 2
        this.ball0.vx = 1
        this.addChild(this.ball0)

        this.ball1 = new Ball(20)
        this.ball1.mass = 1
        this.ball1.x = 300
        this.ball1.y = this.stage.stageHeight / 2
        this.ball1.vx = -1
        this.addChild(this.ball1)

        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this)
    }

    private onEnterFrame(evt: egret.Event): void {
        this.ball0.x += this.ball0.vx
        this.ball1.x += this.ball1.vx

        let dist = this.ball1.x - this.ball0.x

        if (dist < this.ball0.radius + this.ball1.radius) {
            let vxTotal = this.ball0.vx - this.ball1.vx
            let vx0Final = ((this.ball0.mass - this.ball1.mass) * this.ball0.vx + 2 * this.ball1.mass * this.ball1.vx) / (this.ball0.mass + this.ball1.mass)
            let vx1Final = vxTotal + vx0Final

            this.ball0.vx = vx0Final
            this.ball1.vx = vx1Final

            this.ball0.x += this.ball0.vx
            this.ball1.x += this.ball1.vx
        }
    }
}